package com.ruoyi.web.controller.gcgl;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.config.RuoYiConfig;
import com.ruoyi.common.config.ServerConfig;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.core.text.Convert;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.file.FileUploadUtils;
import com.ruoyi.common.utils.file.FileUtils;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.gcgl.domain.GcCcsq;
import com.ruoyi.gcgl.domain.GcYzsp;
import com.ruoyi.gcgl.mapper.GcSendTipMapper;
import com.ruoyi.gcgl.service.IGcCustomerService;
import com.ruoyi.gcgl.service.IGcSendTipService;
import com.ruoyi.gcgl.service.IGcYzspService;
import com.ruoyi.web.controller.tool.AliyunSmsUtils;

/**
 * 印章审批Controller
 * 
 * @author ruoyi
 * @date 2022-11-29
 */
@Controller
@RequestMapping("/gcgl/yzsp")
public class GcYzspController extends BaseController{
	
    private String prefix = "gcgl/yzsp";

    @Autowired
    private IGcYzspService gcYzspService;
    @Autowired
    private IGcCustomerService gcCustomerService;
    @Autowired
    private ServerConfig serverConfig;
    @Autowired
    private IGcSendTipService gcSendTipService;
    @Autowired
    private GcSendTipMapper gcSendTipMapper;
    
    private static final String FILE_DELIMETER = ",";

    @RequiresPermissions("gcgl:yzsp:view")
    @GetMapping()
    public String yzsp(){
        return prefix + "/yzsp";
    }

    /**
     * 查询印章审批列表
     */
    @RequiresPermissions("gcgl:yzsp:list")
    @PostMapping("/list")
    @ResponseBody
    public TableDataInfo list(GcYzsp gcYzsp){
        startPage();
        gcYzsp.setDeleteFlag(1);
        if(getSysUser().isShow43R(getUserId())){
        	gcYzsp.setCreateUser(getLoginName());
        }
        List<GcYzsp> list = gcYzspService.selectGcYzspList(gcYzsp);
        return getDataTable(list);
    }

    /**
     * 导出印章审批列表
     */
    @RequiresPermissions("gcgl:yzsp:export")
    @Log(title = "印章审批", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    @ResponseBody
    public AjaxResult export(GcYzsp gcYzsp){
    	gcYzsp.setDeleteFlag(1);
    	if(getSysUser().isShow()){
            gcYzsp.setCreateUser(getLoginName());
            }
        List<GcYzsp> list = gcYzspService.selectGcYzspList(gcYzsp);
        ExcelUtil<GcYzsp> util = new ExcelUtil<GcYzsp>(GcYzsp.class);
        return util.exportExcel(list, "印章审批数据");
    }

    /**
     * 新增印章审批
     */
    @GetMapping("/add")
    public String add(ModelMap mmap){
    	mmap.put("sqr", getLoginName());
    	mmap.put("riq", new Date());
//    	List<Map> gcCustomerlis = gcCustomerService.selectCustAndSuppAllList();
//    	mmap.put("clis", gcCustomerlis);
        return prefix + "/add";
    }

    /**
     * 新增保存印章审批
     */
    @RequiresPermissions("gcgl:yzsp:add")
    @Log(title = "印章审批", businessType = BusinessType.INSERT)
    @PostMapping("/add")
    @ResponseBody
    public synchronized AjaxResult addSave(GcYzsp gcYzsp){
    	
    	try {
    		SimpleDateFormat sdy = new SimpleDateFormat("yyyy");
    		int year = Integer.parseInt(sdy.format(new Date()));
    		GcYzsp l_gcYzsp = new GcYzsp();
    		List<GcYzsp> lisCount = gcYzspService.selectGcYzspList(l_gcYzsp);
    		String no = String.format("%03d", lisCount.size()+1);
    		gcYzsp.setOrderNo(year+"-"+no);
        	gcYzsp.setStatus(0);
        	gcYzsp.setDeleteFlag(1);
        	gcYzsp.setCreateAt(new Date());
        	gcYzsp.setUpdateAt(new Date());
        	gcYzsp.setCreateUser(getLoginName());
        	gcYzsp.setUpdateUser(getLoginName());
        	gcYzsp.setJbr(getLoginName());
        	gcYzsp.setJbrAt(new Date());
        	gcYzspService.insertGcYzsp(gcYzsp);
        	
        	//发送消息通知
//        	gcSendTipService.sendTip("gzt", "印章审批", gcYzsp.getId().toString(), 
//        			gcYzsp.getCreateUser(), DateUtils.dateTime(gcYzsp.getCreateAt()), 
//        			gcYzsp.getStatus().toString(), null, gcYzsp.getId().toString());
        	
        	try {
//        		List<Map> userlis = gcSendTipMapper.selectGcToUserByName(gcYzsp.getCreateUser());
//        		if(userlis!=null && userlis.size()>0){
//        			String phonenumber = userlis.get(0).get("phonenumber").toString();//创建人
        		String phonenumber = caiw;
        			AliyunSmsUtils.returnSmsTz(phonenumber);
//        		}
			} catch (Exception e) {
				// TODO: handle exception
				e.printStackTrace();
			}
		} catch (Exception e) {
			// TODO: handle exception
			return error(e.getMessage());
		}
    	
        return toAjax(1);
    }

    /**
     * 修改印章审批
     */
    @GetMapping("/edit/{id}")
    public String edit(@PathVariable("id") Long id, ModelMap mmap)
    {
        GcYzsp obj = gcYzspService.selectGcYzspById(id);
        if(obj.getZlwj()!=null && !obj.getZlwj().equals("")){
        	String[] zlis = obj.getZlwj().split(",");
        	String file = "";
        	for(int i=0;i<zlis.length;i++){
        		file += RuoYiConfig.getOnPath()+zlis[i]+",";
        	}
        	mmap.put("zlwjvo", file);
        }
        mmap.put("gcYzsp", obj);
        
//    	List<Map> gcCustomerlis = gcCustomerService.selectCustAndSuppAllList();
//    	mmap.put("clis", gcCustomerlis);
        return prefix + "/edit";
    }

    /**
     * 修改保存印章审批
     */
    @Log(title = "印章审批", businessType = BusinessType.UPDATE)
    @PostMapping("/edit")
    @ResponseBody
    public AjaxResult editSave(GcYzsp gcYzsp){
    	try {
    		gcYzsp.setUpdateAt(new Date());
        	gcYzsp.setUpdateUser(getLoginName());
        	gcYzspService.updateGcYzsp(gcYzsp);
        	
        	try {
//        		List<Map> userlis = gcSendTipMapper.selectGcToUserByName(gcYzsp.getCreateUser());
//        		if(userlis!=null && userlis.size()>0){
//        			String phonenumber = userlis.get(0).get("phonenumber").toString();//创建人
        		String phonenumber = caiw;
        			AliyunSmsUtils.returnSmsTz(phonenumber);
//        		}
			} catch (Exception e) {
				// TODO: handle exception
				e.printStackTrace();
			}
		} catch (Exception e) {
			// TODO: handle exception
			return error(e.getMessage());
		}
    	
        return toAjax(1);
    }

    /**
     * 删除印章审批
     */
    @RequiresPermissions("gcgl:yzsp:remove")
    @Log(title = "印章审批", businessType = BusinessType.DELETE)
    @PostMapping( "/remove")
    @ResponseBody
    public AjaxResult remove(String ids)
    {
        return toAjax(gcYzspService.deleteGcYzspByIds(ids));
    }
    
    @GetMapping("/yzspprint/{id}")
    public String yzspprint(@PathVariable("id") Long id, ModelMap mmap){
    	GcYzsp obj = gcYzspService.selectGcYzspById(id);
        mmap.put("obj", obj);
        return prefix + "/yzspprint";
    }
    
    @GetMapping("/yzspsp/{id}")
    public String yzspsp(@PathVariable("id") Long id, ModelMap mmap){
    	GcYzsp obj = gcYzspService.selectGcYzspById(id);
    	if(obj.getZlwj()!=null && !obj.getZlwj().equals("")){
        	String[] zlis = obj.getZlwj().split(",");
        	String file = "";
        	for(int i=0;i<zlis.length;i++){
        		file += RuoYiConfig.getOnPath()+zlis[i]+",";
        	}
        	obj.setZlwj(file);
        }
        mmap.put("obj", obj);
        mmap.put("downloadZilwj", obj.getZlwj());
        return prefix + "/yzspsp";
    }
    
    //财务审批
    @RequiresPermissions("gcgl:yzsp:cwpsview")
    @GetMapping("/cwps")
    public String cwps()
    {
        return prefix + "/yzspcwps";
    }
    
    @PostMapping("/cwpslist")
    @ResponseBody
    public TableDataInfo cwpslist(GcYzsp gcYzsp)
    {
        startPage();
        gcYzsp.setDeleteFlag(1);
        gcYzsp.setStatus(0);
        List<GcYzsp> list = gcYzspService.selectGcYzspList(gcYzsp);
        return getDataTable(list);
    }
    
    @Log(title = "通过", businessType = BusinessType.UPDATE)
    @PostMapping("/cwyes")
    @ResponseBody
    public AjaxResult cwyes(String ids, ModelMap mmap){
    	String[] id = Convert.toStrArray(ids);
    	for(int i=0;i<id.length;i++){
    		GcYzsp obj = new GcYzsp();
    		obj.setId(Long.parseLong(id[i]));
    		obj.setStatus(1);
    		obj.setBgr(getLoginName());
    		obj.setBgrAt(new Date());
    		gcYzspService.updateGcYzsp(obj);
    	}
    	
    	try {
//    		List<Map> userlis = gcSendTipMapper.selectGcToUserByName(gcYzsp.getCreateUser());
//    		if(userlis!=null && userlis.size()>0){
//    			String phonenumber = userlis.get(0).get("phonenumber").toString();//创建人
    		String phonenumber = zjl;
    			AliyunSmsUtils.returnSmsTz(phonenumber);
//    		}
		} catch (Exception e) {
			// TODO: handle exception
			e.printStackTrace();
		}
    	
    	return toAjax(1);
    }
    
    @Log(title = "不通过", businessType = BusinessType.UPDATE)
    @PostMapping("/cwno")
    @ResponseBody
    public AjaxResult cwno(String ids, ModelMap mmap){
    	String[] id = Convert.toStrArray(ids);
    	for(int i=0;i<id.length;i++){
    		GcYzsp obj = new GcYzsp();
    		obj.setId(Long.parseLong(id[i]));
    		obj.setStatus(2);
    		obj.setBgr(getLoginName());
    		obj.setBgrAt(new Date());
    		gcYzspService.updateGcYzsp(obj);
    		
    		try {
        		List<Map> userlis = gcSendTipMapper.selectGcToUserByName(obj.getCreateUser());
        		if(userlis!=null && userlis.size()>0){
        			String phonenumber = userlis.get(0).get("phonenumber").toString();//创建人
        			AliyunSmsUtils.returnSmsTz(phonenumber);
        		}
    		} catch (Exception e) {
    			// TODO: handle exception
    			e.printStackTrace();
    		}
    	}
    	
    	
    	return toAjax(1);
    }
    
    /////总经理审批
    @RequiresPermissions("gcgl:yzsp:zjlpsview")
    @GetMapping("/zjlps")
    public String zjlps()
    {
        return prefix + "/yzspzjlps";
    }
    
    @PostMapping("/zjlpslist")
    @ResponseBody
    public TableDataInfo zjlpslist(GcYzsp gcYzsp)
    {
        startPage();
        gcYzsp.setDeleteFlag(1);
        gcYzsp.setStatus(0);
        List<GcYzsp> list = gcYzspService.selectGcYzspList(gcYzsp);
        return getDataTable(list);
    }
    
    @Log(title = "通过", businessType = BusinessType.UPDATE)
    @PostMapping("/zjlyes")
    @ResponseBody
    public AjaxResult zjlyes(String ids, ModelMap mmap){
    	String[] id = Convert.toStrArray(ids);
    	for(int i=0;i<id.length;i++){
    		GcYzsp obj = new GcYzsp();
    		obj.setId(Long.parseLong(id[i]));
    		obj.setStatus(3);
    		obj.setSpr(getLoginName());
    		obj.setSprAt(new Date());
    		gcYzspService.updateGcYzsp(obj);
    		
    		GcYzsp gcYzsp = gcYzspService.selectGcYzspById(Long.parseLong(id[i]));
    		//发送消息通知
//        	gcSendTipService.sendTip("gzt", "印章审批", gcYzsp.getId().toString(), 
//        			gcYzsp.getCreateUser(), DateUtils.dateTime(gcYzsp.getCreateAt()), 
//        			gcYzsp.getStatus().toString(), null, gcYzsp.getId().toString());
    		
    		try {
        		List<Map> userlis = gcSendTipMapper.selectGcToUserByName(gcYzsp.getCreateUser());
        		if(userlis!=null && userlis.size()>0){
        			String phonenumber = userlis.get(0).get("phonenumber").toString();//创建人
        			AliyunSmsUtils.returnSmsTz(phonenumber);
        		}
			} catch (Exception e) {
				// TODO: handle exception
				e.printStackTrace();
			}
    	}
    	
    	return toAjax(1);
    }
    
    @Log(title = "不通过", businessType = BusinessType.UPDATE)
    @PostMapping("/zjlno")
    @ResponseBody
    public AjaxResult zjlno(String ids, ModelMap mmap){
    	String[] id = Convert.toStrArray(ids);
    	for(int i=0;i<id.length;i++){
    		GcYzsp obj = new GcYzsp();
    		obj.setId(Long.parseLong(id[i]));
    		obj.setStatus(4);
    		obj.setSpr(getLoginName());
    		obj.setSprAt(new Date());
    		gcYzspService.updateGcYzsp(obj);
    		
    		GcYzsp gcYzsp = gcYzspService.selectGcYzspById(Long.parseLong(id[i]));
    		//发送消息通知
//        	gcSendTipService.sendTip("gzt", "印章审批", gcYzsp.getId().toString(), 
//        			gcYzsp.getCreateUser(), DateUtils.dateTime(gcYzsp.getCreateAt()), 
//        			gcYzsp.getStatus().toString(), null, gcYzsp.getId().toString());
    		
    		try {
        		List<Map> userlis = gcSendTipMapper.selectGcToUserByName(gcYzsp.getCreateUser());
        		if(userlis!=null && userlis.size()>0){
        			String phonenumber = userlis.get(0).get("phonenumber").toString();//创建人
        			AliyunSmsUtils.returnSmsTz(phonenumber);
        		}
			} catch (Exception e) {
				// TODO: handle exception
				e.printStackTrace();
			}
    	}
    	return toAjax(1);
    }
    
    /**
     * 通用上传请求（多个）
     */
    @PostMapping("/uploads")
    @ResponseBody
    public AjaxResult uploadFiles(List<MultipartFile> files) throws Exception{
        try
        {
            // 上传文件路径
            String filePath = RuoYiConfig.getUploadPath();
            List<String> urls = new ArrayList<String>();
            List<String> fileNames = new ArrayList<String>();
            List<String> newFileNames = new ArrayList<String>();
            List<String> originalFilenames = new ArrayList<String>();
            for (MultipartFile file : files)
            {
                // 上传并返回新文件名称
                String fileName = FileUploadUtils.upload(filePath, file);
                String url = serverConfig.getUrl() + fileName;
                urls.add(url);
                fileNames.add(fileName);
                newFileNames.add(FileUtils.getName(fileName));
                originalFilenames.add(file.getOriginalFilename());
            }
            AjaxResult ajax = AjaxResult.success();
            ajax.put("urls", StringUtils.join(urls, FILE_DELIMETER));
            ajax.put("fileNames", StringUtils.join(fileNames, FILE_DELIMETER));
            ajax.put("newFileNames", StringUtils.join(newFileNames, FILE_DELIMETER));
            ajax.put("originalFilenames", StringUtils.join(originalFilenames, FILE_DELIMETER));
            return ajax;
        }
        catch (Exception e)
        {
            return AjaxResult.error(e.getMessage());
        }
    }
}